package com.skvalex.transport;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockMapActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.skvalex.transport.utils.LocationHelper;
import com.skvalex.transport.utils.TelephonyUtils;
import com.skvalex.transport.vehicle.Vehicle;
import com.skvalex.transport.vehicle.VehicleTracker;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MyLocationOverlay;
import com.skvalex.transport.map.ExtendedMapView;

import java.util.TimerTask;

/**
 * User: alexey.emelyanenko@gmail.com
 * Date: 4/15/12 9:34 PM
 * <p/>
 * Modified by skvalex@gmail.com
 */
public class MainActivity extends SherlockMapActivity {

    private static final String TAG = "MapActivity";
    private ExtendedMapView mapView;
    private Handler mHandler = new Handler();
    private TimerTask timerTask = new MapUpdateTimerTask();
    private VehicleTracker vehicleTracker;
    private MyLocationOverlay mylocationOverlay;
    private LocationManager locationManager;

    public class MapUpdateTimerTask extends TimerTask {
        @Override
        public void run() {
            Log.d(TAG, "START Timer Update " + Thread.currentThread().getName() + " with time " + Settings.getRefreshPeriodInMs());
            vehicleTracker.syncVehicles();
            mHandler.postDelayed(this, Settings.getRefreshPeriodInMs());
        }
    }

    private Runnable immediateUpdate = new Runnable() {
        @Override
        public void run() {
            if (timerTask != null) {
                timerTask.cancel();
            }
            mHandler.removeCallbacks(timerTask);
            mHandler.postDelayed(timerTask, 0);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.ab_bg_black));
        getSupportActionBar().setSplitBackgroundDrawable(getResources().getDrawable(R.drawable.ab_bg_black));
        mapView = (ExtendedMapView) findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(false);
        mapView.displayZoomControls(false);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mylocationOverlay = new MyLocationOverlay(mapView.getContext(), mapView);
        mylocationOverlay.enableMyLocation();
        mapView.getOverlays().add(mylocationOverlay);
        vehicleTracker = new VehicleTracker(mapView);
        mapView.setVehicleTracker(vehicleTracker);
        mapView.getController().setZoom(Settings.getDefaultZoom());
        moveToCurrentLocation();
    }

    private void restoreApplicationState() {
        if (Settings.isShowBusFlagEnabled()) {
            vehicleTracker.startTrack(Vehicle.BUS);
        } else {
            vehicleTracker.stopTrack(Vehicle.BUS);
        }
        if (Settings.isShowTrolleyFlagEnabled()) {
            vehicleTracker.startTrack(Vehicle.TROLLEY);
        } else {
            vehicleTracker.stopTrack(Vehicle.TROLLEY);
        }
        if (Settings.isShowTramFlagEnabled()) {
            vehicleTracker.startTrack(Vehicle.TRAM);
        } else {
            vehicleTracker.stopTrack(Vehicle.TRAM);
        }
        mapView.setSatellite(Settings.getMapType() == Settings.MAP_TYPE_SATELLITE);
        mHandler.postDelayed(timerTask, 0);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 3, mylocationOverlay);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 3, mylocationOverlay);
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "onResume");
        restoreApplicationState();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mHandler.removeCallbacks(timerTask);
        super.onPause();
    }

    @Override
    protected void onStop() {
        mHandler.removeCallbacks(timerTask);
        locationManager.removeUpdates(mylocationOverlay);
        super.onStop();
    }

    private void moveToCurrentLocation() {
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        Location locationGps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (LocationHelper.isBetterLocation(locationGps, location)) {
            location = locationGps;
        }

        if (location != null) {
            GeoPoint currentPoint = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
            MapController controller = mapView.getController();
            controller.animateTo(currentPoint, immediateUpdate);
        } else {
            Toast.makeText(getApplicationContext(), R.string.cannot_get_current_location, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.current_location: {
                moveToCurrentLocation();
                break;
            }
            case R.id.refresh: {
                if (TelephonyUtils.isOnline(this)) {
                    mHandler.removeCallbacks(immediateUpdate);
                    mHandler.postDelayed(immediateUpdate, 0);
                } else {
                    Toast.makeText(getApplicationContext(), R.string.network_is_not_available, Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case R.id.settings: {
                startActivity(new Intent(this, Settings.class));
                break;
            }
        }
        return true;
    }
}
